var models  = require('../models');
var settings = require('../config')


function UserManager(options){
    this.core = options.core;
    this.settings = options.settings;
}
UserManager.prototype.list = function(options){
    return models.User.findOne({
        where :{
            uid : uid
        }
    })
}

UserManager.prototype.get = function(uid){
    //return promomise object
    return models.User.findOne({
        where :{
            uid : uid
        }
    })
}
UserManager.prototype.getUserByUserName = function(username){
    return models.User.findOne({
        where :{
            username : username
        }
    })
}
UserManager.prototype.create = function(user){

}

UserManager.prototype.update = function(user,onlyupdatecache){
    
    var client = this.core.client
    client.set('uid' + user.id,JSON.stringify(user),settings.redis.userttl)
    client.expire('uid' + user.id,settings.redis.userttl)
    //this.core.emit('account:update',user)
    if (!!onlyupdatecache && onlyupdatecache == 'onlyupdatecache'){
        return new Promise(function(resolve,reject){
            resolve(user); 
        })
    }else{
        var uid = user.id
        delete user.update_time
        delete user.id
        return models.User.update(user,{where :{id: uid}})
    }
    
}

UserManager.prototype.getUserByUid = function(uid){
    var client = this.core.client
    let that = this;
    return new Promise(function(resolve,reject){
        client.get("uid" + uid,function(err,userjson){
            if (!!userjson){
                try{
                    var _user = JSON.parse(userjson);
                    resolve(_user)
                    return 
                }catch(e){}
            }
            try {
                models.User.findOne({
                    where: {
                        id: uid
                    }
                }).then(function (dbuser) {

                    if(dbuser!=null){
                        // dbuser.name = encodeURI(dbuser.name)
                        console.log(typeof settings.redis.userttl)
                        client.set("uid" + uid, JSON.stringify(dbuser.toJSON()));
                        client.expire(key,settings.redis.userttl)
                        resolve(dbuser.toJSON())
                    }else{
                        resolve();
                    }

                }).catch(function (error) {
                    reject(error)
                })
            }catch (e){
                console.log(e);
                reject(e)
            }
            
        })
    })
    
    
}


UserManager.prototype.findOrCreateUser = function(profile,options,done){
    var Passport = models.Passport;
    var User = models.User;
    var state = options.state || "";
    Passport.findOne({'where': {'identifier': profile.openid},include:[User]}).then(function(pp){
        if (!pp){//按照openid没找到东西
            Passport.findOne({'where':{'union_id':profile.unionid},include:[User]}).then(function(pp2){
                if(!!pp2){
                    //通过unionid找到用户，返回用户，并且将刚刚的登陆过程的Openid存到数据库里面
                    Passport.create({
                        identifier : profile.openid,
                        protocol : options.protocol,
                        username : pp2.username,
                        headimg : pp2.headimg,
                        provider : options.provider,
                        union_id : profile.unionid,
                        uid : pp2.uid
                    }).then(function(u){
                        return done(null,pp2.User.toJSON() )   
                    })
                }else{//begin else 1
                    if(state == 'base'){
                        //如果是小授权，则直接返回
                        var user = {id : 'temp', sex: profile.sex || "-1" , openid: profile.openid, desc : 'temp'}
                        return done(null,user)
                    }else{//begin else 2
                        User.create({
                            // name : encodeURI(profile.nickname),
                            sex : profile.sex, 
                            headimg : profile.headimgurl                               
                        }).then(function(_user){
                            _user.createPassport({
                                protocol : options.protocol,//setting.auth.options.wechat.protocol,
                                provider : options.provider,//setting.auth.options.wechat.provider,
                                username : encodeURI(profile.nickname),
                                identifier : profile.openid,
                                union_id : profile.unionid,
                                headimg : profile.headimgurl,
                            }).then(function(_pp){
                                return done(null,_user.toJSON())
                            })
                        })
                    }//end else 2
                }//end else 1
            })
        }else{
            return done(null, pp.User.toJSON());
        } 
        /** */
        //create user and return    
    },function(err){
        console.log('err occur',err);
        return done(null, false, {
            message: 'Some fields did not validate.'
        });
    });
}

module.exports = UserManager;